package com.pospi.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;

import com.google.gson.Gson;
import com.lany.sp.SPHelper;
import com.maning.updatelibrary.InstallUtils;
import com.mylhyl.circledialog.CircleDialog;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.been.UpDateBeen;
import com.pospi.pai.yunpos.cash.PointActivity;
import com.pospi.pai.yunpos.login.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by acer on 2018/11/13.
 */

public class DownUtil {
    private Context context;

    public DownUtil(Context context) {
        this.context = context;
    }

    public  void downCus() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getperson");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.CUS_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }
        });
    }
    public  void initMsg(final Handler handler) {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "syspara.msg");
        params.put("fun", "getmsg");
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                try {
                    JSONObject object = new JSONObject(Response);
                    String errCode = object.getString("errCode");
                    if (errCode.equals("100")) {
                        int count = object.getInt("count");
                        Message message = Message.obtain();
                        message.what = 9;
                        message.arg1 = count;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 9;
                        message.arg1 = 0;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 9;
                    message.arg1 = 0;
                    handler.sendMessage(message);
                }
            }
        });
    }
    public void checkVertion(final FragmentManager manager){
        Map<String, String> map = new HashMap<>();
        new HttpConnection().Net(map, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("update", Response);
                final UpDateBeen been = new Gson().fromJson(Response, UpDateBeen.class);
                if (been.getVersionCode() > getVersionCode(context)) {
                    new AlertDialog.Builder(context).setMessage("检测到版本更新\n"+been.getChangeLog()+"\n请点击[升级]开始下载。")
                            .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                   downApk(been.getApkUrl(),manager);
                                }
                            })
                            .setNegativeButton("取消", null).show();
                }
            }
        });

    }
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    public  void downApk( String url,FragmentManager manager){
        showProgress(manager);
        //下载APK
        InstallUtils.with(context)
                //必须-下载地址
                .setApkUrl(url)
                //非必须-下载保存的文件的完整路径+/name.apk，使用自定义路径需要获取读写权限
                .setApkPath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/xstore/update.apk")
                //非必须-下载回调
                .setCallBack(new InstallUtils.DownloadCallBack() {
                    @Override
                    public void onStart() {
                        //下载开始
                    }
                    @Override
                    public void onComplete(String path) {
                        //下载完成
                        //安装APK
                        /**
                         * 安装APK工具类
                         * @param activity       上下文
                         * @param filePath      文件路径
                         * @param callBack      安装界面成功调起的回调
                         */
                        InstallUtils.installAPK((Activity) context, path, new InstallUtils.InstallCallBack() {
                            @Override
                            public void onSuccess() {
                                //onSuccess：表示系统的安装界面被打开
                                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                            }

                            @Override
                            public void onFail(Exception e) {
                            }
                        });
                    }

                    @Override
                    public void onLoading(long total, long current) {
//                        //下载中
//                        //内部做了处理，onLoading 进度转回progress必须是+1，防止频率过快
                        int progress = (int) (current * 100 / total);
//                        tv_progress.setText(progress + "%");
                        builder.setProgress((int) total, (int) current);
                        builder.setProgressText("已下载").create();

                    }

                    @Override
                    public void onFail(Exception e) {
                        //下载失败
                    }

                    @Override
                    public void cancle() {
                        //下载取消
                    }
                })
                //开始下载
                .startDownload();
    }
    private CircleDialog.Builder builder;
    private void showProgress(FragmentManager manager){
        builder = new CircleDialog.Builder();
        builder.setCancelable(false).setCanceledOnTouchOutside(false)
                .setTitle("下载")
                .setProgressText("开始下载")
                .setWidth(0.4f)
//                        .setProgressText("已经下载%s了")

//                        .setProgressDrawable(R.drawable.bg_progress_h)
                .show(manager);

    }
}
